package com.daocao.jy.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spanned;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.daocao.jy.R;
import com.daocao.jy.api.Api;
import com.daocao.jy.api.bean.BuyLevelBean;
import com.daocao.jy.api.bean.PaymentBean;
import com.daocao.jy.api.model.LeveListModel;
import com.daocao.jy.base.BaseActivity;
import com.daocao.jy.constant.Const;
import com.daocao.jy.constant.UserInfoGlobal;
import com.daocao.jy.util.Dialog;
import com.daocao.jy.util.Network;
import com.daocao.jy.util.RxLifeUtil;
import com.daocao.jy.util.Spans;
import com.daocao.jy.util.ToastUtil;
import com.daocao.jy.util.UI;
import com.daocao.jy.view.V19FrameLayout;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.beecloud.BCPay;
import cn.beecloud.BeeCloud;
import cn.beecloud.async.BCCallback;
import cn.beecloud.async.BCResult;
import cn.beecloud.entity.BCPayResult;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class VipPacketSecondActivity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.img_icon)
    ImageView imgIcon;
    @BindView(R.id.txt_status)
    TextView txtStatus;
    @BindView(R.id.txt_tips_one)
    TextView txtTipsOne;
    @BindView(R.id.txt_tips_two)
    TextView txtTipsTwo;
    @BindView(R.id.img_icon_sec)
    ImageView imgIconSec;
    @BindView(R.id.txt_info_sec)
    TextView txtInfoSec;
    @BindView(R.id.txt_status_sec)
    TextView txtStatusSec;
    @BindView(R.id.txt_tips_one_sec)
    TextView txtTipsOneSec;
    @BindView(R.id.txt_tips_two_sec)
    TextView txtTipsTwoSec;
    @BindView(R.id.img_icon_three)
    ImageView imgIconThree;
    @BindView(R.id.txt_info)
    TextView txtInfo;
    @BindView(R.id.txt_status_three)
    TextView txtStatusThree;
    @BindView(R.id.txt_tips_one_three)
    TextView txtTipsOneThree;
    @BindView(R.id.txt_tips_two_three)
    TextView txtTipsTwoThree;
    @BindView(R.id.txt_info_three)
    TextView txtInfoThree;
    private ArrayList<LeveListModel.DatasBean> levelList;

    private Unbinder unbiner;
    private int x24;
    private int x30;
    private int x36;
    private int x18;
    private ProgressDialog progressDialog;
    private PayHandler mHandler;
    private String toastMsg;
    private String selectWays;
    private static final String WX_APP = "WX_APP";
    private static final String ALI_APP = "ALI_APP";
    private static final String ACCOUNT = "BAG";
    private int selectBuy = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vip_packet_second);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        levelList = getIntent().getParcelableArrayListExtra("data");
        txtTitle.setText("会员套餐");
        txtRight.setText("价格说明");
        txtRight.setVisibility(View.VISIBLE);
        if (levelList != null && levelList.size() != 0) {

            x18 = getResources().getDimensionPixelSize(R.dimen.x18);
            x24 = getResources().getDimensionPixelSize(R.dimen.x24);
            x30 = getResources().getDimensionPixelSize(R.dimen.x30);
            x36 = getResources().getDimensionPixelSize(R.dimen.x36);
            for (int i = 0; i < levelList.size(); i++) {
                LeveListModel.DatasBean item = levelList.get(i);
                switch (i) {
                    case 0:
                        Spanned textOne = Spans.with(this).font("￥", x30, 0xffffffff).
                                font(item.money, x36, 0xffFB5E01).
                                font("元", x18, 0xffffffff).
                                font("\n银卡会员", x24, 0xffFEFEFE).
                                build();
                        txtInfo.setText(textOne);
                        UI.setTvHtml(txtTipsTwo, R.string.vip_packet_sec, Float.valueOf(item.sale) / 10 + "", Float.valueOf(item.term_sale) / 10 + "", item.uolevel_rate + "%", item.utlevel_rate + "%");
                        break;
                    case 1:
                        Spanned textTwo = Spans.with(this).font("￥", x30, 0xffffffff).
                                font(item.money, x36, 0xffFB5E01).
                                font("元", x18, 0xffffffff).
                                font("\n金卡会员", x24, 0xffFEFEFE).
                                build();
                        txtInfoSec.setText(textTwo);
                        UI.setTvHtml(txtTipsTwoSec, R.string.vip_packet_sec, Float.valueOf(item.sale) / 10 + "", Float.valueOf(item.term_sale) / 10 + "", item.uolevel_rate + "%", item.utlevel_rate + "%");

                        break;
                    case 2:
                        Spanned textThree = Spans.with(this).font("￥", x30, 0xffffffff).
                                font(item.money, x36, 0xffFB5E01).
                                font("元", x18, 0xffffffff).
                                font("\n铂金会员", x24, 0xffFEFEFE).
                                build();
                        txtInfoThree.setText(textThree);
                        UI.setTvHtml(txtTipsTwoThree, R.string.vip_packet_sec, Float.valueOf(item.sale) / 10 + "", Float.valueOf(item.term_sale) / 10 + "", item.uolevel_rate + "%", item.utlevel_rate + "%");

                        break;
                }
            }
        }
        if (UserInfoGlobal.getUserLevel() == 1) {
            txtStatus.setText("当前等级");
            txtStatusSec.setText("立即购买");
            txtStatusThree.setText("立即购买");
        } else if (UserInfoGlobal.getUserLevel() == 2) {
            txtStatus.setText("已获等级");
            txtStatusSec.setText("当前等级");
            txtStatusThree.setText("立即购买");
        } else if (UserInfoGlobal.getUserLevel() == 3) {
            txtStatus.setText("已获等级");
            txtStatusSec.setText("已获等级");
            txtStatusThree.setText("当前等级");
        }
        initPay();
        mHandler = new PayHandler(this);
    }

    //    ===========================余额支付===========================
    public void getBagPayment(String order_no) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }


        loadingDialog.show();
        PaymentBean bean = new PaymentBean();
        bean.order_no = order_no;
        Api.api_service.getBagPayment(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(this, "支付成功");
                });
    }
    //    ===========================余额支付===========================
    //    ===========================会员等级升级（提交订单）===========================
    private void getBuyLevel(String level_id, String pay_way) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        BuyLevelBean bean = new BuyLevelBean();
        bean.level_id = level_id;
        bean.pay_way = pay_way;
        Api.api_service.getBuyLevel(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
//                    ToastUtil.makeText(this, "购买成功");
                    if (selectWays.equals(ACCOUNT)) {
                        getBagPayment(result.datas.order_no);
                    } else {
                        goToPay("支付", result.datas.money, result.datas.order_no);
                    }
                });
    }
    //    ===========================会员等级升级（提交订单）===========================


    //    ===========================获取支付方式===========================
    public void getPaymentList() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
        loadingDialog.show();
        Api.api_service.getPaymentList().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    Dialog.showRechargeTypeDialog(this, result.datas, new Dialog.DialogPaymentClickListener() {
                        @Override
                        public void confirm(String name, String id) {
                            if (selectBuy == 1) {
                                if (levelList != null && levelList.size() >= 2)
                                    getBuyLevel(levelList.get(1).id + "", id);
                            } else if (selectBuy == 2) {
                                if (levelList != null && levelList.size() >= 3)
                                    getBuyLevel(levelList.get(2).id + "", id);
                            }
                        }

                    });
                });
    }
//    ===========================获取支付方式===========================


    @Override
    protected void onDestroy() {
        super.onDestroy();
        BCPay.detachWechat();
        bcCallback = null;
        mHandler = null;
        //清理当前的activity引用
        BCPay.clear();
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.txt_status, R.id.txt_status_sec, R.id.txt_status_three, R.id.btn_back, R.id.txt_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.txt_status:
                break;
            case R.id.txt_status_sec:
                selectBuy = 1;
                if (UI.toString(txtStatusSec).equals("立即购买")) {
                    getPaymentList();
                }
                break;
            case R.id.txt_status_three:
                selectBuy = 2;
                if (UI.toString(txtStatusThree).equals("立即购买")) {
                    getPaymentList();
                }
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.txt_right:
                Dialog.showVipPacketTips(this);
                break;
        }
    }


    private void initPay() {
        // 推荐在主Activity或application里的onCreate函数中初始化BeeCloud.
//        if (!Const.IS_DEBUG) {
//            BeeCloud.setSandbox(true);
//
////        测试Appid和secret
//            BeeCloud.setAppIdAndSecret("956fb30c-0579-4469-aa31-64140d64e61c",
//                    "e32e1f0d-d219-4c76-8585-13f953327123");
//        } else {
        BeeCloud.setSandbox(false);
        //     正式网Appid和secret
        BeeCloud.setAppIdAndSecret(Const.BeeCloud.APP_ID,
                Const.BeeCloud.APP_Secret);
//        }


        // 如果用到微信支付，在用到微信支付的Activity的onCreate函数里调用以下函数.
        // 第二个参数需要换成你自己的微信AppID.
//        wx8f9ffda903463ae8
        String initInfo = BCPay.initWechatPay(this, Const.BeeCloud.WECHAT_ID);
        if (initInfo != null) {
            Toast.makeText(this, "微信初始化失败：" + initInfo, Toast.LENGTH_LONG).show();
        }
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("处理中，请稍候...");
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(true);
    }


    private void goToPay(String title, double money, String bill_no) {
//        Map<String, String> mapOptional = new Gson().fromJson(PayOrderitem.optional, new TypeToken<HashMap<String, String>>() {
//        }.getType());
//        Map<String, String> mapOptional = new HashMap<>();
//        mapOptional.put("action", PayOrderitem.optional.action);
//        Map<String, String> mapOptional = new HashMap<>();
//        mapOptional.put("disable_pay_channels", "credit_group");
        if (selectWays.equals(ALI_APP)) {
//                    支付宝
            progressDialog.show();
//            BCPay.getInstance(PayTypeActivity.this).reqAliPaymentAsync(
//                    PayOrderitem.title,
//                    PayOrderitem.order_money * 100,
//                    PayOrderitem.notice_sn,
//                    mapOptional,
//                    bcCallback);
            BCPay.getInstance(this).reqAliPaymentAsync(
                    title,
                    (int) (money * 100),
                    bill_no,
                    null,
                    bcCallback);
        } else if (selectWays.equals(WX_APP)) {
//                    微信
            progressDialog.show();
            //对于微信支付, 手机内存太小会有OutOfResourcesException造成的卡顿, 以致无法完成支付
            //这个是微信自身存在的问题
//            Log.i("dasdasddas", BCPay.isWXAppInstalledAndSupported() + "aa" + BCPay.isWXPaySupported());
            if (BCPay.isWXAppInstalledAndSupported() &&
                    BCPay.isWXPaySupported()) {

//                BCPay.getInstance(this).reqWXPaymentAsync(
//                        PayOrderitem.title,               //订单标题
//                        PayOrderitem.order_money * 100,  //金额
//                        PayOrderitem.notice_sn,  //订单流水号
//                        mapOptional,            //扩展参数(可以null)
//                        bcCallback);            //支付完成后回调入口
                BCPay.getInstance(this).reqWXPaymentAsync(
                        title,               //订单标题
                        (int) (money * 100),  //金额
                        bill_no,  //订单流水号
                        null,            //扩展参数(可以null)
                        bcCallback);            //支付完成后回调入口

            } else {
                ToastUtil.makeText(this,
                        "您尚未安装微信或者安装的微信版本不支持").show();
                progressDialog.dismiss();
            }
        }
    }

    private static class PayHandler extends Handler {
        WeakReference<VipPacketSecondActivity> mActivityReference;

        PayHandler(VipPacketSecondActivity activity) {
            mActivityReference = new WeakReference<VipPacketSecondActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final VipPacketSecondActivity activity = mActivityReference.get();
            if (activity != null) {
                switch (msg.what) {
                    case 1:
                        //如果用户手机没有安装银联支付控件,则会提示用户安装
                        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                        builder.setTitle("提示");
                        builder.setMessage("完成支付需要安装或者升级银联支付控件，是否安装？");

                        builder.setNegativeButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
//                                        UPPayAssistEx.installUPPayPlugin(activity);
                                        dialog.dismiss();
                                    }
                                });

                        builder.setPositiveButton("取消",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                        builder.create().show();
                        break;
                    case 2:
                        Toast.makeText(activity, activity.toastMsg, Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }
    }


    //支付结果返回入口
    private BCCallback bcCallback = new BCCallback() {
        @Override
        public void done(final BCResult bcResult) {
            final BCPayResult bcPayResult = (BCPayResult) bcResult;
            //此处关闭loading界面
            progressDialog.dismiss();

            //根据你自己的需求处理支付结果
            String result = bcPayResult.getResult();
            /*
              注意！
              所有支付渠道建议以服务端的状态金额为准，此处返回的RESULT_SUCCESS仅仅代表手机端支付成功
            */
            Message msg = mHandler.obtainMessage();
            //单纯的显示支付结果
            msg.what = 2;
            if (result.equals(BCPayResult.RESULT_SUCCESS)) {
                toastMsg = "用户支付成功";
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        getReportResult(money, "1", notice_sn);
                    }
                });
            } else if (result.equals(BCPayResult.RESULT_CANCEL))
                toastMsg = "用户取消支付";
            else if (result.equals(BCPayResult.RESULT_FAIL)) {
                toastMsg = "支付失败, 原因: " + bcPayResult.getErrCode() +
                        " # " + bcPayResult.getErrMsg() +
                        " # " + bcPayResult.getDetailInfo();

                /**
                 * 你发布的项目中不应该出现如下错误，此处由于支付宝政策原因，
                 * 不再提供支付宝支付的测试功能，所以给出提示说明
                 */
                if (bcPayResult.getErrMsg().equals("PAY_FACTOR_NOT_SET") &&
                        bcPayResult.getDetailInfo().startsWith("支付宝参数")) {
                    toastMsg = "支付失败：由于支付宝政策原因，故不再提供支付宝支付的测试功能，给您带来的不便，敬请谅解";
                }

                /**
                 * 以下是正常流程，请按需处理失败信息
                 */

                if (bcPayResult.getErrMsg().equals(BCPayResult.FAIL_PLUGIN_NOT_INSTALLED)) {
                    //银联需要重新安装控件
                    msg.what = 1;
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        getReportResult(money, "2", notice_sn);
                    }
                });

            } else if (result.equals(BCPayResult.RESULT_UNKNOWN)) {
                //可能出现在支付宝8000返回状态
                toastMsg = "订单状态未知";
            } else {
                toastMsg = "invalid return";
            }

            mHandler.sendMessage(msg);

            /*
            if (bcPayResult.getId() != null) {
                //你可以把这个id存到你的订单中，下次直接通过这个id查询订单
                Log.w(TAG, "bill id retrieved : " + bcPayResult.getId());

                //根据ID查询，此处只是演示如何通过id查询订单，并非支付必要部分
                getBillInfoByID(bcPayResult.getId());
            }
            */
        }
    };
}
